package netty

import io.netty.bootstrap.Bootstrap
import io.netty.channel.*
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel


class NettyClient {
    fun start(port:Int): Channel {
        // 创建EventLoopGroup，用于处理客户端的I/O操作
        val groupThread: EventLoopGroup = NioEventLoopGroup()

        // 创建Bootstrap实例，客户端启动对象
        val bootstrap = Bootstrap()
        bootstrap.group(groupThread)
        try {
            // 设置服务端Channel类型为NioSocketChannel作为通道实现
            bootstrap.channel(NioSocketChannel::class.java)


            // 设置客户端处理
            // 设置客户端处理
            bootstrap.handler(object : ChannelInitializer<SocketChannel>() {
                @Throws(Exception::class)
                override fun initChannel(socketChannel: SocketChannel) {
                    socketChannel.pipeline().addLast(RpcDecoder)
                    socketChannel.pipeline().addLast(RpcEncoder)
                    socketChannel.pipeline().addLast(ClientHandler)
                }
            })

            // 绑定端口
            val channelFuture = bootstrap.connect("localhost", port).sync()

            channelFuture.addListener(ChannelFutureListener {
                if (channelFuture.isSuccess) {
                    println("连接服务器成功")
                } else {
                    println("连接服务器失败")
                    channelFuture.cause().printStackTrace()
                    groupThread.shutdownGracefully() //关闭线程组
                }
            })

            return channelFuture.channel()
        } catch (e: InterruptedException) {
            throw RuntimeException(e)
        } finally {
            // 优雅地关闭线程
            println("finally")
            //groupThread.shutdownGracefully();
        }
    }
}